import React from "react";

// 导入路由
import { Route } from 'react-router-dom'

// 导入TabBar对应的组件  
import Index from '../Index'
import News from '../News'
import List from '../List'
import Profile from '../Profile'

// 导入TabBar
import { TabBar } from 'antd-mobile';

// 导入组件自己的样式
import './index.css'

// TabBar 数据
const tabItens = [
  {
    id: '01',
    title: '首页',
    icon: 'icon-home',
    path: '/home'
  },
  {
    id: '02',
    title: '找房',
    icon: 'icon-dituzhaofang',
    path: '/home/list'
  },
  {
    id: '03',
    title: '资讯',
    icon: 'icon-zixun',
    path: '/home/news'
  },
  {
    id: '04',
    title: '个人中心',
    icon: 'icon-wode',
    path: '/home/profile'
  }
]

export default class Home extends React.Component {
  state = {
    // 默认选中的TabBar菜单项
    selectedTab: this.props.location.pathname,
  };

  componentDidUpdate(prevProps){
    if(this.props.location.pathname !== prevProps.location.pathname){
      // 此时，路由发生切换了，更新选中的TabBar菜单项
      this.setState(()=>{ 
        return {
          selectedTab: this.props.location.pathname
        }
      })
    }
  }

  // 渲染TabBar,Item
  renderContent() {
    return tabItens.map(item => {
      return <TabBar.Item
        title={item.title}
        key={item.id}
        icon={<i className={`iconfont ${item.icon}`} />}
        selectedIcon={<i className={`iconfont ${item.icon}`} style={{ color: "#28886d" }} />}
        selected={this.state.selectedTab === item.path}
        onPress={() => {
          this.setState({
            selectedTab: item.path,
          })
          // 路由切换
          this.props.history.push(item.path)  // 相当于 Link组件或理解为a标签
        }}
      />
    })

  }

  render() {
    // console.log(this.props.location.pathname); // 获取路由名称
    return <div className="home" >
      {/* 2.3 渲染子路由*/}
      <Route path="/home" exact component={Index}></Route>
      <Route path="/home/list" component={List}></Route>
      <Route path="/home/news" component={News}></Route>
      <Route path="/home/profile" component={Profile}></Route>

      {/* TabBar */}
      <TabBar tintColor="#28886d">
        {/* 调用renderContent方法，渲染TabBar，Item */}
        {this.renderContent()}
      </TabBar>
    </div>
  }
}